import { ref, reactive, onMounted, getCurrentInstance, onActivated, toRefs, watch } from 'vue';

interface listRequest {
	list: any[];
	pageNo: string | number;
	pageIndex: string | number;
	pageSize: string | number;
	totalPage: string | number;
	totalRows: string | number;
	loading: boolean;
}

// 表格分页，关键字搜素
const getTableData = <K = string>(postMethod: Function, requestParams?: {}, searchObj: any = reactive({}), fetchDataInLife: boolean = true, watchSearchKeys: boolean = true) => {
	
	let reactiveData = reactive<listRequest>({
		list: [], // 数组
		pageNo: 1, // 当前页
		pageIndex: 1,
		pageSize: 20, // 一页的数量
		totalRows: 0, // 总条数
		loading: false, // 加载状态
		totalPage: 0, // 总页数
	});

	let timer: any = null;

	// 获取列表数据
	const getData = async (filter = {}) => {
		try {
			reactiveData.loading = true;
			let params = {
				pageNo: reactiveData.pageNo,
				pageSize: reactiveData.pageSize,
				...requestParams,
				...searchObj,
				...filter,
			};
			let res = await postMethod(params);
			if (res.code != 200) {
				throw Error(res.message);
			}
			if(res.data.totalRows || res.data.totalRows === 0){
				reactiveData.totalRows = res.data.totalRows;
			}else if(res.data.totalCount || res.data.totalCount === 0){
				reactiveData.totalRows = res.data.totalCount;
			}
			if(res.data.rows || res.data.rows === 0){
				reactiveData.list = res.data.rows;
			}else if(res.data.items){
				reactiveData.list = res.data.items;
			}
			// let item = res.data[0]
			// for(let i = 0; i< 20; i++) {
			//     reactiveData.tableData.push(item)
			// }
	
			reactiveData.loading = false;
			// console.log(reactiveData.tableData)
		} catch (e) {
			console.log(e);
			reactiveData.loading = false;
		}
	};

	//页数改变时
	const handleCurrentChange = (pageIndex: number | string) => {
		reactiveData.pageNo = pageIndex;
		getData();
	};

	// 一页条数改变
	const handleSizeChange = (pageSize: number | string) => {
		reactiveData.pageSize = pageSize;
		getData();
	};

	// 关键字搜索
	const filterHandle = (filter: any, delay = 500) => {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			reactiveData.pageSize = 20;
			reactiveData.pageNo = 1;
			getData(filter);
		}, delay);
	};

	// 设置序列号
	const indexMethod = (index: number) => {
		if (reactiveData.pageNo > 1) {
			return index + 1 + (Number(reactiveData.pageNo) - 1) * Number(reactiveData.pageSize);
		} else {
			return index + 1;
		}
	};

	onMounted(async () => {
		// 是否在onMounted请求数据
		if (fetchDataInLife) {
			await getData();
		}
	});

	if (watchSearchKeys) {
		watch(searchObj, () => {
			filterHandle(reactive);
		});
	}
	const searchHandle = () => {
		reactiveData.pageSize = 20;
		reactiveData.pageNo = 1;
		getData();
	}
	
	return {
		...toRefs(reactiveData),
		getData,
		handleCurrentChange,
		handleSizeChange,
		filterHandle,
		indexMethod,
		searchHandle,
	};
};

export default getTableData;
